package run.halo.app.core.endpoint.theme;

import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
import static org.springdoc.core.fn.builders.parameter.Builder.parameterBuilder;

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.fn.builders.operation.Builder;
import org.springdoc.webflux.core.fn.SpringdocRouteBuilder;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import run.halo.app.core.extension.content.ProductType;
import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion;
import run.halo.app.extension.ListResult;
import run.halo.app.extension.ReactiveExtensionClient;
import run.halo.app.extension.router.SortableRequest;

/**
 * Endpoint for product type query APIs.
 *
 * @author halo-product-management
 * @since 2.0.0
 */
@Component
@RequiredArgsConstructor
public class ProductTypeQueryEndpoint implements CustomEndpoint {

    private final ReactiveExtensionClient client;

    @Override
    public RouterFunction<ServerResponse> endpoint() {
        final var tag = "ProductTypeV1alpha1Public";
        return SpringdocRouteBuilder.route()
            .GET("product-types", this::listProductTypes,
                builder -> {
                    builder.operationId("queryProductTypes")
                        .description("Lists product types.")
                        .tag(tag)
                        .response(responseBuilder()
                            .implementation(ListResult.generateGenericClass(ProductType.class))
                        );
                    ProductTypePublicQuery.buildParameters(builder);
                }
            )
            .GET("product-types/{name}", this::getByName,
                builder -> builder.operationId("queryProductTypeByName")
                    .description("Gets product type by name.")
                    .tag(tag)
                    .parameter(parameterBuilder()
                        .in(ParameterIn.PATH)
                        .name("name")
                        .description("Product type name")
                        .required(true)
                    )
                    .response(responseBuilder()
                        .implementation(ProductType.class)
                    )
            )
            .build();
    }

    private Mono<ServerResponse> getByName(ServerRequest request) {
        String name = request.pathVariable("name");
        return client.get(ProductType.class, name)
            .flatMap(productType -> ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(productType)
            );
    }

    private Mono<ServerResponse> listProductTypes(ServerRequest request) {
        ProductTypePublicQuery query = new ProductTypePublicQuery(request.exchange());
        return client.listBy(ProductType.class, query.toListOptions(), query.toPageRequest())
            .flatMap(result -> ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(result)
            );
    }

    public static class ProductTypePublicQuery extends SortableRequest {
        public ProductTypePublicQuery(ServerWebExchange exchange) {
            super(exchange);
        }

        public static void buildParameters(Builder builder) {
            SortableRequest.buildParameters(builder);
        }
    }

    @Override
    public GroupVersion groupVersion() {
        return PublicApiUtils.groupVersion(new ProductType());
    }
}